package controller

import (
	"github.com/gin-gonic/gin"
	"go-demo/common"
	"go-demo/model"
	"go-demo/service"
	"net/http"
	"strconv"
)

type CommentListResponse struct {
	model.Response
	CommentList []model.Comment `json:"comment_list,omitempty"`
}

type CommentActionResponse struct {
	model.Response
	Comment model.Comment `json:"comment,omitempty"`
}

//登录用户对视频进行评论

// token string 用户鉴权token 必需
// video_id string 视频id 必需
// action_type string 必需 1-发布评论，2-删除评论
// comment_text string 可选
// 用户填写的评论内容，在action_type=1的时候使用
// comment_id string 可选
// 要删除的评论id，在action_type=2的时候使用
func CommentAction(c *gin.Context) {
	token := c.Query("token")
	actionType := c.Query("action_type")
	videoId, _ := strconv.ParseInt(c.Query("video_id"), 10, 64)
	if user, exist := common.UsersLoginInfo[token]; exist {

		//从token中可以得到用户id
		if actionType == "1" {
			text := c.Query("comment_text")
			commentFormat := service.CreateComment(user, videoId, text)
			c.JSON(http.StatusOK, CommentActionResponse{Response: model.Response{StatusCode: common.SUCCESS, StatusMsg: "评论操作成功"},
				Comment: model.Comment{
					Id:         commentFormat.Id,
					User:       user,
					Content:    text,
					CreateDate: commentFormat.CreateDate,
				}})
			return
		} else {
			commentId, _ := strconv.ParseInt(c.Query("comment_id"), 10, 64)
			service.DeleteCommentByID(commentId)
			c.JSON(http.StatusOK, model.Response{StatusCode: common.SUCCESS, StatusMsg: "删除操作成功"})
		}
		c.JSON(http.StatusOK, model.Response{StatusCode: common.SUCCESS, StatusMsg: "操作成功"})
	} else {
		c.JSON(http.StatusOK, model.Response{StatusCode: common.ERROR, StatusMsg: "操作失败"})
	}
}

func CommentList(c *gin.Context) {
	videoId, _ := strconv.ParseInt(c.Query("video_id"), 10, 64)
	commentList := service.CommentList(videoId)
	c.JSON(http.StatusOK, CommentListResponse{
		Response:    model.Response{StatusCode: common.SUCCESS, StatusMsg: "操作成功"},
		CommentList: commentList,
	})
}
